<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import request from "@/common/utils/request";
import { CloseOutlined, SearchOutlined } from "@ant-design/icons-vue";
import { nanoid } from "nanoid";
import { message } from "ant-design-vue";

const emit = defineEmits(["selectScript:selects"]);

const props = defineProps({
  // 脚本数量, 最多五个
  scriptArrLength: {
    type: Number,
    default: 0,
  },
  // 当前使用的脚本数组
  useScript: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  visible: false,
  submitLoading: false,
  // 获取列表loding
  getListLoading: false,
  // 头部搜索
  serchData: {
    // 脚本关键词
    keyword: "",
    // 邮箱
    // mailbox: '',
    page: 1,
    pageSize: 10,
  },

  total: 0,
  last_page: 0,
  // 脚本列表
  list: [],
});

const showList = computed({
  get() {
    state.list.forEach((ele) => {
      checkValidate(ele);
    });
    return state.list;
  },
});

// 勾选的脚本项
const selects = computed(() => {
  if (!state.list.length) return [];
  // 勾选 并且没有被使用过
  // && !ele.disabled
  const selects = state.list.filter((ele) => ele.select);
  console.log(selects, "勾选的没有被使用过的项");
  return selects;
});

// 确定按钮禁用逻辑
const submitDisabled = computed(() => {
  if (props.scriptArrLength >= 5) return true;
  const filterList = selects.value.filter((item) =>
    props.useScript.some((ele) => ele.id == item.id)
  );
  if (selects.value.length - filterList.length <= 0) return true;
  return false;
});

// 发起搜索
const serch = () => {
  state.serchData.page = 1;
  getList("serch");
};

// 勾选某项
const selectItem = (item) => {
  !item.disabled && (item.select = !item.select);
  // if (props.scriptArrLength + selects.value.length + 1 <= 5) {
  //     item.select = !item.select
  // }
};

// 点击确定
const submitConfirm = () => {
  const filterList = selects.value.filter(
    (item) => !props.useScript.some((ele) => ele.id == item.id)
  );
  emit("selectScript", JSON.parse(JSON.stringify(filterList)));
  message.success("导入成功!");
  drawerControl.close();
};

// 获取列表
const getList = async (type = "") => {
  if (type == "reset") {
    resetQueryData();
  }
  state.getListLoading = true;
  const res = await request.get(
    "/work_ai",
    "/user/shotstack/scripttext/list",
    state.serchData
  );
  console.log(res, "列表结果");
  state.total = res.result.total;
  state.last_page = res.result.last_page;

  if (type == "reset" || type == "serch") {
    state.list = res.result.data;
  } else {
    state.list.push(...res.result.data);
  }
  resetChecked();

  state.getListLoading = false;
};

// 滚动加载逻辑
const handleScroll = (event) => {
  const container = event.target;
  // 判断是否滚动到底部
  if (
    container.scrollTop + container.clientHeight >=
    container.scrollHeight - 10
  ) {
    // 如果没有在加载中，并且还有数据要加载
    if (!state.getListLoading && state.serchData.page < state.last_page) {
      state.serchData.page++;
      getList();
    }
  }
};

// 判断脚本是否被使用, 以及能否使用
const checkValidate = (ele) => {
  const find = props.useScript.find((item) => item.id === ele.id);
  // 使用了, 并且内容没有变化, 并且已勾选
  console.log(
    !(props.scriptArrLength + selects.value.length + 1 <= 5),
    "满了5个"
  );
  console.log(selects.value, "勾选的项");

  // 回显, 禁用的勾选项
  const filterSelect = selects.value.filter((item) =>
    props.useScript.some((ele) => ele.id == item.id)
  );

  // 还可以选择多少
  //  + filterSelect.length
  const selectNum = 5 - (props.scriptArrLength - filterSelect.length);

  console.log(selectNum, "还能选几个-----------------");

  if (!!find && find.content == ele.content && ele.select) {
    ele.disabled = true;
    ele.show = false;
    ele.msg = "此脚本已勾选，不可重复勾选";
  } else if (selects.value.length >= selectNum) {
    if (ele.select) {
      ele.disabled = false;
      ele.show = true;
      ele.msg = "";
    } else {
      ele.disabled = true;
      ele.msg =
        "当前脚本选择已达到上限5条，请先删除已有脚本内容，才可以继续选择";
      ele.show = false;
    }
  } else {
    ele.show = true;
    ele.msg = "";
    ele.disabled = false;
  }
};

// 回显勾选的逻辑
const resetChecked = () => {
  state.list.forEach((ele) => {
    const find = props.useScript.find((i) => i.id == ele.id);
    if (find) {
      ele.select = true;
    } else {
      ele.select = false;
    }
  });
};

// 重置列表数据
const resetQueryData = () => {
  state.serchData = {
    // 脚本关键词
    keyword: "",
    // 分页信息
    page: 1,
    pageSize: 10,
  };
};

// 开关控制
const drawerControl = {
  open: () => {
    state.visible = true;
    getList();
  },
  close: () => {
    resetQueryData();
    state.list = [];
    state.visible = false;
  },
};

defineExpose({
  drawerControl,
});
</script>

<template>
  <a-drawer
    v-if="state.visible"
    v-model:visible="state.visible"
    class="custom-class"
    style="color: red; min-width: 790px; z-index: 200 !important"
    placement="right"
    :bodyStyle="{
      paddingTop: 0,
    }"
    :closable="false"
    destroyOnClose
    :maskClosable="false"
    :keyboard="true"
    width="790px"
  >
    <slot name="title">
      <div class="title_box">
        <div class="title_top">
          <h1 class="title">文案库 (共{{ state.list.length }}条)</h1>
          <!-- {{ props.scriptArrLength + 'props.scriptArrLength' }}
                    {{ selects.length + 'selects.value.length' }} -->
          <div class="close" @click="drawerControl.close">
            <CloseOutlined />
          </div>
        </div>
      </div>
    </slot>

    <div class="content">
      <div class="content_serch">
        <a-input
          class="serch_item"
          allowClear
          v-model:value="state.serchData.keyword"
          @change="(e) => e.type == 'click' && serch()"
          placeholder="请输入脚本关键词"
        >
          <template #suffix>
            <SearchOutlined
              @click.stop="serch"
              class="serch_icon"
            ></SearchOutlined>
          </template>
        </a-input>
        <!-- <a-input class="serch_item" v-model:value="state.serchData.mailbox" placeholder="请输入创作者邮箱">
                    <template #suffix>
                        <SearchOutlined @click="serch" class="serch_icon"></SearchOutlined>
                    </template>
                </a-input> -->
      </div>

      <div class="script_list_box" @scroll="handleScroll($event)">
        <template v-if="state.list.length">
          <div
            class="script_list_item"
            @click="selectItem(item)"
            v-for="item in showList"
            :key="item.id"
          >
            <div class="script_list_item_athermsg">
              <span class="script_name">{{ item.title }}</span>
              <!-- <div class="creat_from">创作者: <span>{{ item.creat_at }}</span></div> -->
            </div>
            <div class="script_list_item_title">
              <div class="msg_time_box">
                创建时间 <span class="msg_time">{{ item.created_at }}</span>
              </div>
              <div class="msg_time_box">
                更新时间 <span class="msg_time">{{ item.updated_at }}</span>
              </div>
            </div>
            <p class="script_list_item_content">
              {{ item.content }}
            </p>
            <div class="script_list_item_footer">
              <template v-if="item.show">
                <div class="controls_right">
                  <a-checkbox
                    v-model:checked="item.select"
                    :disabled="item.disabled"
                  >
                    <span @click.stop="() => {}">选择脚本</span>
                  </a-checkbox>
                </div>
              </template>
              <template v-else>
                <a-tooltip placement="topLeft">
                  <template #title>
                    <span>{{ item.msg }}</span>
                  </template>
                  <a-checkbox
                    v-model:checked="item.select"
                    :disabled="item.disabled"
                  >
                    <span @click.stop="() => {}">选择脚本</span>
                  </a-checkbox>
                </a-tooltip>
              </template>
            </div>
          </div>
        </template>

        <template v-else>
          <a-empty />
        </template>
      </div>
    </div>

    <template #footer>
      <div style="display: flex; justify-content: flex-end">
        <a-button style="margin-right: 15px" @click="drawerControl.close"
          >取消</a-button
        >
        <a-button
          type="primary"
          @click="submitConfirm"
          :loading="state.submitLoading"
          :disabled="submitDisabled"
          >确定</a-button
        >
      </div>
    </template>
  </a-drawer>
</template>

<style lang="less" scoped>
@gao: calc(100% - 64px);
@bdc: #d6d6d6;

:deep(.ss-drawer-wrapper-body) {
  background-color: #f2f5fd !important;
}

.title_box {
  width: 100%;
  padding-bottom: 10px;
  padding-top: 24px;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 999;

  &::after {
    content: "";
    height: 1px;
    width: calc(100% + 48px);
    background-color: #e8e8e8;
    position: absolute;
    bottom: 0;
    left: -24px;
  }

  .title_top {
    display: flex;
    justify-content: space-between;
    color: #0c0d0e;

    // margin-bottom: 10px;
    h1 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .close {
      cursor: pointer;
      text-align: center;
      line-height: 29px;
      padding: 0 6px;

      &:hover {
        background-color: #f3f3f4;
      }
    }
  }

  .title_bottom {
    .btn_prev {
      border-radius: 5px;
      padding: 0 16px;
      font-size: 12px;
      height: 28px;
    }
  }
}

.content {
  color: #000000;
  display: flex;
  flex-direction: column;
  padding-top: 30px;
  gap: 30px;
  width: 100%;
  height: @gao;

  .content_serch {
    display: flex;
    gap: 15px;

    .serch_item {
      width: 249px;
    }

    .serch_icon {
      font-size: 18px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        color: var(--ss-primary-color-hover);
      }
    }
  }

  .script_list_box {
    display: flex;
    flex-direction: column;
    gap: 50px 0;
    padding-top: 30px;
    padding-bottom: 20px;
    padding-right: 3px;
    // padding: 20px;
    // padding: 50px 20px 20px 20px;
    height: 100%;
    overflow-y: auto;

    &::-webkit-scrollbar {
      /* 滚动条的宽度 */
      width: 8px;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      /* 滑块的背景颜色 */
      border-radius: 10px;
      /* 滑块的圆角 */
    }

    .script_list_item {
      border: 1px solid @bdc;
      border-radius: 8px;
      position: relative;
      cursor: pointer;

      // 脚本容器外面的脚本名称和创建人
      .script_list_item_athermsg {
        position: absolute;
        left: 0;
        top: -25px;
        width: 100%;
        display: flex;
        justify-content: space-between;

        .script_name {
          font-weight: 600;
        }

        .creat_from {
          font-size: 13px;

          span {
            margin-left: 10px;
          }
        }
      }

      // 脚本标题
      .script_list_item_title {
        display: flex;
        gap: 0 30%;
        padding: 15px 30px;
        font-size: 13px;
        border-bottom: 1px solid @bdc;

        .msg_time_box {
          .msg_time {
            color: #888;
            margin-left: 20px;
          }
        }
      }

      // 脚本文案内容
      .script_list_item_content {
        padding: 15px;
        line-height: 1.2;
        margin: 0;
      }

      // 脚本底部的勾选
      .script_list_item_footer {
        border-top: 1px solid @bdc;
        padding: 5px 15px;
      }
    }
  }
}
</style>
